package com.gulimall.search.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.gulimall.search.config.GulimallElasticSearchConfig;
import com.gulimall.search.constant.EsConstant;
import com.gulimall.search.service.ElasticSearchSaveService;
import com.gulimall.search.to.product.SkuEsModelTo;
import lombok.extern.log4j.Log4j2;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author by董江
 * @Tool Intellij IDEA
 * @Classname ElasticSearchSaveServiceImpl
 * @Date 2022/5/11 15:15
 */
@Log4j2
@Service
public class ElasticSearchSaveServiceImpl implements ElasticSearchSaveService {
    @Autowired
    private RestHighLevelClient client;

    /**
     * 保存要上架的sku数据
     * @param skuEsModelTos
     */
    @Override
    public boolean productStatusUp(List<SkuEsModelTo> skuEsModelTos) throws IOException {
        //1、建立索引。product，建立映射文件

        //2、批量将数据添加到bulk请求中
        BulkRequest bulkRequest = new BulkRequest();

        for (SkuEsModelTo skuEsModelTo : skuEsModelTos) {
            //构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            //id
            indexRequest.id(skuEsModelTo.getSkuId().toString());
            //以JSON类型存入，先将数据模型转为JSON类型
            String jsonString = JSONObject.toJSONString(skuEsModelTo);
            indexRequest.source(jsonString, XContentType.JSON);

            bulkRequest.add(indexRequest);
        }

        //进行保存
        BulkResponse bulkResponse = client.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
        //判断请求中是否有错误，有:TRUE
        boolean hasFailures = bulkResponse.hasFailures();
        if (!hasFailures) {
            //收集成功上架的商品id
            List<String> collect = Arrays.stream(bulkResponse.getItems()).map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            log.info("商品上架成功：【{}】",collect);
            return true;
        }
        log.info("商品上架发生错误");
        return false;
    }
}
